<?php

require_once 'classes/LightPressPlugin.php';

class Akismet extends LightPressPlugin {
    
    // ported from Matt Mullenweg's Akismet 1.14, http://akismet.com
    
    var $constructor_args = array();
    var $default_context = 24; // LP_CONTEXT_POST | LP_CONTEXT_STATIC
    var $description = 'Use the Akismet service to check for comment spam';
    
    var $active = true;
    var $hooks = array('insert_comment');
    
    var $_wordpress_api_key;
    var $_ksd_api_host;
    
    function Akismet(&$frontend, $args, $dummy_run=false) {
        $this->LightPressPlugin($frontend, $args, $dummy_run);
        if (!$dummy_run) {
            if (!isset($frontend->options['wordpress_api_key'])) {
                $this->active = false;
            } else {
                $this->_wordpress_api_key = $frontend->options['wordpress_api_key'];
                $this->_ksd_api_host = $this->_wordpress_api_key . '.rest.akismet.com';
            }
        }
    }
    
    function run($hook, &$payload) {
        // payload structure: date author email url comment type approved
        /* WP comment structure
        ["comment_post_ID"]=>  int(536)
        ["comment_author"]=>  string(4) "ludo"
        ["comment_author_email"]=>  string(11) "ludo@qix.it"
        ["comment_author_url"]=>  string(14) "http://qix.it/"
        ["comment_content"]=>  string(4) "test"
        ["comment_type"]=>  string(0) ""
        ["user_ID"]=>  NULL
         */
        $comment = array(
            'comment_post_ID'=>0,
            'comment_author'=>$payload['author'],
            'comment_author_email'=>$payload['email'],
            'comment_author_url'=>$payload['url'],
            'comment_content'=>$payload['comment'],
            'comment_type'=>$payload['type'],
            'user_ID'=>null);
        $comment['user_ip'] = $_SERVER['REMOTE_ADDR'];
        $comment['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
        $comment['referrer'] = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
        $comment['blog'] = $this->_frontend->options['url'];
        foreach ($_SERVER as $k=>$v) {
            if ($k == 'HTTP_COOKIE' || is_array($v))
                continue;
            $comment[$k] = $v;
        }
        $qs = '';
        foreach ($comment as $k=>$v)
            $qs .= $k . '=' . urlencode(stripslashes($v)) . '&';
        $response = $this->_ksd_http_post($qs);
        if (is_array($response) && isset($response[1])) {
            if ($response[1] == 'true') {
                // spam, update akismet spam count option and mark comment as spam
                $payload['approved'] = 'spam';
                $db =& $this->_frontend->db;
                if ($db->query("select option_value from {$this->_frontend->tables['options']} where option_name = 'akismet_spam_count'"))
                    $db->query("update {$this->_frontend->tables['options']} set option_value = option_value + 1 where option_name = 'akismet_spam_count'");
                else
                    $db->query("insert into {$this->_frontend->tables['options']} (option_name, option_value) values ('akismet_spam_count', 1)");
            } else {
                // approve comment
                $payload['approved'] = '1';
            }
            $this->_ksd_delete_old();
        }
    }
    
    function install() {
        // check that the Akismet WP plugin is activated
        if (!in_array('akismet/akismet.php', get_settings('active_plugins')))
            return "please activate the Akismet WP plugin before activating its LP frontend";
        // no need to check for a valid key, since Akismet keeps nagging the user
        // about it on every WP page until a valid key is entered
    }
    
    function _ksd_http_post($qs) {
        // ksd_http_post($query_string, $ksd_api_host, '/1.1/comment-check', $ksd_api_port);
        $req = array();
        $req[] = 'POST /1.1/comment-check HTTP/1.0';
        $req[] = "Host: {$this->_ksd_api_host}";
        $req[] = "Content-Type: application/x-www-form-urlencoded; charset={$this->_frontend->options['charset']}";
        $req[] = "Content-Length: " . strlen($qs);
        $req[] = "User-Agent: WordPress/{$this->_frontend->options['wp_version']} | Akismet/1.14";
        $req[] = '';
        $req[] .= $qs;
        $response = '';

        $f = @fsockopen($this->_ksd_api_host, 80, $errno, $errstr, 3);
        if ($f !== false) {
            fwrite($f, implode("\r\n", $req));
            while (!feof($f))
                $response .= fgets($f, 1160);
            fclose($f);
            $response = explode("\r\n\r\n", $response, 2);
        } else {
            die("error fetching Akismet response, $errno $errstr");
        }

        return $response;
    }
    
    function _ksd_delete_old() {
        /*
        global $wpdb;
        $now_gmt = current_time('mysql', 1);
        $wpdb->query("DELETE FROM $wpdb->comments WHERE DATE_SUB('$now_gmt', INTERVAL 15 DAY) > comment_date_gmt AND comment_approved = 'spam'");
        $n = mt_rand(1, 5);
        if ( $n % 5 )
		$wpdb->query("OPTIMIZE TABLE $wpdb->comments");
         */
        $now = gmdate("Y-m-d H:i:s");
        $this->_frontend->db->query("delete from {$this->_frontend->tables['comments']} where comment_date_gmt < '$now' - interval 15 day and comment_approved = 'spam'");
        if (mt_rand(1,5) % 5)
            $this->_frontend->db->query("optimize table {$this->_frontend->tables['comments']}");
    }
    
}

?>
